<?php
// -----------------------------------------------------------------------------
// sdefastsearch - A PHP Fast ESP Search API
// Copyright (C) 2008,2009 sueddeutsche.de GmbH, Hultschiner Str. 8, D-81677 München
// www.sueddeutsche.de.de - Andreas.Scheerer@sueddeutsche.de
//
// This file is part of sdefastsearch.
//
// sdefastsearch is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------

/**
 * Example implementation of a web search with result drilldown by navigators.
 * 
 * @author  Andreas Scheerer <Andreas.Scheerer@sueddeutsche.de>
 * @version $Id: navSearch.php 11 2009-08-23 04:23:33Z andreas.scheerer $ 
 */

//--------------------------------------------------------------------------
//---                               config                               ---
//-------------------------------------------------------------------------- 
set_include_path(dirname(__FILE__).'/../../../src/');
error_reporting(E_ALL^E_NOTICE);

$cfg_host       = 'localhost';
$cfg_port       = 15100;
$cfg_view       = 'default';
$cfg_numHits    = 10;
$cfg_searchType = 'navigation';
$cfg_queryOpts  = 'mode="simpleall", annotation_class="user"';
$cfg_queryId    = 'simplesearch';
$cfg_numNavHits = 5;

//--------------------------------------------------------------------------
//---                               includes                             ---
//-------------------------------------------------------------------------- 
require_once 'sde/fastsearch/SearchFactory.php';
require_once 'sde/fastsearch/SearchException.php';
require_once 'sde/fastsearch/query/Query.php';
require_once 'sde/fastsearch/result/QueryTransformationName.php';

//--------------------------------------------------------------------------
//---                                 main                               ---
//-------------------------------------------------------------------------- 
// get vars
$queryStr = trim(urldecode($_GET["query"]));
$page     = (int)$_GET["page"];
$debug    = (boolean)$_GET["debug"];

if ($page < 1) {
    $page = 1; 
}

$nav = rawurldecode(trim($_GET["nav"]));
$drilldown = rawurldecode(trim($_GET["drilldown"])); 
$drillup   = rawurldecode(trim($_GET["drillup"]));

// drill down
if (!empty($drilldown)) {
    $nav = $nav." ".$drilldown;
}

// drill up
if (!empty($drillup)) {
    $nav = str_replace($drillup, "", $nav);
}

// base get url based on given parameters
$baseGetURL = $_SERVER['PHP_SELF']."?query=".urlencode($queryStr)."&nav=".urlencode($nav);

// calculate offset
$offset = ($page-1)*$cfg_numHits;

// search 
$errorMsg  = "";
$debugMsg  = "";
$documentsIter = null;
$navIter = null;
$totalHits = 0;
$numPages  = 0;

try {
    $queryResult = getSearchResult($cfg_host, $cfg_port, $cfg_view, 
        $queryStr, $cfg_numHits, $offset, $cfg_queryId, $cfg_queryOpts, $nav);
    
    // matching documents    
    $documentsIter = $queryResult->documents();

    // matching navigators
    $navIter = $queryResult->navigators();
    
    // TODO if totalhits > 4000 (see doc) limit
    $totalHits = $queryResult->getDocCount();
    $debugMsg  = $queryResult->getHttpSearchURL();
    
    // paging
    $numPages   = ceil($totalHits/$cfg_numHits);
    if ($page < $numPages) $showNextPaging = true;
    if ($page > 1) $showLastPaging = true;  
    
} catch (SearchException $e) {
    $errorMsg = $e->getMessage(); 
}

// prepare template data
$templData['searchType'] = $cfg_searchType;
$templData['baseGetURL'] = $baseGetURL;
if (empty($errorMsg)) {
    $templData['errorMsg'] = ($debug)?"debug: ".$debugMsg:"";
    $templData['showLastPaging'] = $showLastPaging;
    $templData['showNextPaging'] = $showNextPaging; 
    $templData['page']  = $page;
    $templData['numPages'] = $numPages;
    $templData['query'] = $queryStr;
    $templData['totalHits'] = $totalHits;
    $templData['documentsIter']= $documentsIter;
    
    // navigators
    $templData['numNavHits'] = $cfg_numNavHits; 
    $templData['navIter'] = $navIter;
    $templData['navStr'] = $nav;
    $showNavigation = true;
    $showResults = true;
} else {
    $templData['errorMsg'] = $errorMsg;
    $showNavigation = false;
    $showResults = false;
}

//print_r($templData);

// display
require '../tpl/head.tpl.php';
require '../tpl/searchform.tpl.php';
if ($showNavigation) require '../tpl/navigation.tpl.php';
if ($showResults) require '../tpl/resultlist.tpl.php';
require '../tpl/foot.tpl.php';


//--------------------------------------------------------------------------
//---                               functions                            ---
//-------------------------------------------------------------------------- 

/**
 * Perfoms a search and returns an QueryResult instance. If anything goes 
 * wrong, a SearchException is thrown.
 *
 * @param string $host
 * @param int    $port
 * @param string $viewName
 * @param string $queryStr
 * @param int    $numHits
 * @param int    $offset
 * @throws SearchException
 */
function getSearchResult ($host, $port, $viewName, $queryStr, $numHits, 
    $offset=0, $queryid="simplesearch", $queryStrOptions="", $navigation="") {
    // Properties
    $properties = array (
        'fastsearch.SearchFactory' => "http.HttpSearchFactory",
        'fastsearch.http.qservers' => "$host:$port"
        );
    
    try {
        // Get searchfactory
        $searchFactory = SearchFactory::newInstance($properties);
    
        // Get view.
        $view = $searchFactory->getSearchView($viewName);
        
        $queryStr = trim($queryStr);
        $queryStr = str_replace('"', '\"', $queryStr);
        $queryStr = 'string("'.$queryStr.'", '.$queryStrOptions.')';
        
        $theQuery = new Query();
        $theQuery->setQueryString($queryStr);
        $theQuery->setParameterByType(BaseParameter::HITS,  $numHits);        
        $theQuery->setParameterByType(BaseParameter::OFFSET,$offset);
        $theQuery->setParameterByName('queryid',$queryid);
                
        // enable navigation
        $theQuery->setParameterByType(BaseParameter::NAVIGATION, 'true');
        if (!empty($navigation)) {
            $theQuery->setParameterByType(BaseParameter::NAVIGATION_FILTER, $navigation);
        }
        
        return $view->search($theQuery);
            
    } catch (Exception $e) {
        throw new SearchException($e->getMessage()); 
    }
}
